package com.novel.service;

import com.novel.common.exception.CustomerException;
import com.novel.mapper.NovelMapper;
import com.novel.mapper.NovelRewardMapper;
import com.novel.mapper.UserMapper;
import com.novel.pojo.novel.Novel;
import com.novel.pojo.novel.NovelReward;
import com.novel.pojo.system.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class NovelRewardService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NovelMapper novelMapper;

    @Autowired
    private NovelRewardMapper novelRewardMapper;


    /**
     * 打赏小说
     * 1.扣钱
     * 2.小说打赏增加
     * 3.给作者加钱
     * 4.增加打赏记录
     */
    @Transactional
    public boolean rewardNovelByNovelId(NovelReward novelReward) {
        //用户扣钱
        User reward = userMapper.selectByPrimaryKey(novelReward.getUserId());
        if (reward.getAmount() < novelReward.getRewardMoney()) {
            throw new CustomerException("余额不足");
        }
        reward.setAmount(reward.getAmount() - novelReward.getRewardMoney());
        userMapper.updateByPrimaryKey(reward);
        //小说打赏数增加
        Novel novel = novelMapper.selectByPrimaryKey(novelReward.getNovelId());
        novel.setRewardAmount(novel.getRewardAmount() + novelReward.getRewardMoney());
        novelMapper.updateByPrimaryKey(novel);
        //作者增加虚拟币
        User author = userMapper.selectByPrimaryKey(novel.getAuthorId());
        author.setAmount(author.getAmount() + novelReward.getRewardMoney() * 0.8d);
        userMapper.updateByPrimaryKey(author);
        //增加打赏记录
        novelReward.setBalance(reward.getAmount());
        return novelRewardMapper.insert(novelReward) == 1;
    }

    /**
     * 根据作者id查询打赏数量map
     */
    public List<Map<String, Object>> getRewardMap(String authorId) {
        return novelRewardMapper.queryNovelRewardByAuthorId(authorId);
    }
}